package cn.xiaoxiang.basic.service.impl;

import cn.xiaoxiang.basic.config.BussinessException;
import cn.xiaoxiang.basic.constants.LoginKou;
import cn.xiaoxiang.basic.constants.Register;
import cn.xiaoxiang.basic.dto.BinderDto;
import cn.xiaoxiang.basic.dto.LoginDto;
import cn.xiaoxiang.basic.dto.SmsCodeLoginDto;
import cn.xiaoxiang.basic.dto.WechatDto;
import cn.xiaoxiang.basic.jwt.JwtUtils;
import cn.xiaoxiang.basic.jwt.RsaUtils;
import cn.xiaoxiang.basic.jwt.UserInfo;
import cn.xiaoxiang.basic.mapper.BaseMapper;
import cn.xiaoxiang.basic.service.LoginService;
import cn.xiaoxiang.basic.util.AjaxResult;
import cn.xiaoxiang.basic.util.HttpUtil;
import cn.xiaoxiang.basic.util.MD5Utils;
import cn.xiaoxiang.basic.util.StrUtils;
import cn.xiaoxiang.org.domain.Employee;
import cn.xiaoxiang.org.domain.Shop;
import cn.xiaoxiang.org.mapper.EmployeeMapper;
import cn.xiaoxiang.org.mapper.ShopMapper;
import cn.xiaoxiang.system.domain.Menu;
import cn.xiaoxiang.system.domain.Permission;
import cn.xiaoxiang.system.mapper.MenuMapper;
import cn.xiaoxiang.system.mapper.PermissionMapper;
import cn.xiaoxiang.user.domain.Logininfo;
import cn.xiaoxiang.user.domain.User;
import cn.xiaoxiang.user.domain.Wxuser;
import cn.xiaoxiang.user.mapper.LogininfoMapper;
import cn.xiaoxiang.user.mapper.UserMapper;
import cn.xiaoxiang.user.mapper.WxuserMapper;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopMapper shopMapper;
//    @Value("${jwt.rsa.pri}")
//    private String privateKey;
    @Value("${jwt.pet.pri}")
    private String jwtPetPri;
    @Override
    public HashMap<String, Object> getAccount(LoginDto dto) {
        //校验参数
        //2.账号是否存在
        Logininfo logininfo=logininfoMapper.findByAccount(dto);
        if(null==logininfo){
            throw new BussinessException("账号或者密码错误，请输入正确的账号或者密码");
        }
        //3.密码是否正确
        String s = MD5Utils.encrypByMd5(logininfo.getSalt() + dto.getPassword());
        String password = logininfo.getPassword();
        if(!password.equals(s)){
            throw new BussinessException("账号或者密码错误，请输入正确的账号或者密码");
        }
        return getMap(logininfo);
    }


    @Override
    public HashMap<String, Object> smsCode(SmsCodeLoginDto sms) {
        //校验参数
        //2.账号是否存在
        Logininfo logininfo = logininfoMapper.smsCode(sms);
        if (null == logininfo) {
            throw new BussinessException("账号或者密码错误，请输入正确的账号或者密码");
        }
        //4.两次验证码是否超过60秒
        Long tll = redisTemplate.getExpire(String.format(Register.REGISTER_PHONE_KEY, sms.getAccount()));
        if (null != tll && tll > ((Register.IMAGE_CODE - 1) * 60)) {
            throw new BussinessException("请超过60秒后发送");
        }
        //5.手机验证码是否过期
        String smsCode = "";
        String sm = (String) redisTemplate.opsForValue().get(String.format(Register.REGISTER_PHONE_KEY, sms.getAccount()));
        if (StringUtils.isNotBlank(sm)) {
            smsCode = sm;
        } else {
            smsCode = StrUtils.getComplexRandomString(4);
        }
        log.info("手机号验证码为：{}", smsCode);
        return getMap(logininfo);
    }

    private HashMap<String, Object> getMap(Logininfo logininfo) {
        //使用jwt
        HashMap<String, Object> map = new HashMap<>();
        try {
            // 创建一个userinfo实体 这里面包含着三个字段 分别是 用户数据 和 两个权限
            // 因为我们生成jwt传的方法里面 需要传入这个实体
            UserInfo userInfo = new UserInfo();
            // 直接可以将用户数据set进去
            userInfo.setLogininfo(logininfo);
            // 生成一个token 通过 uuid
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(jwtPetPri).getFile());
            // 我们需要判断 它是后台用户 才存在 两个权限 前台用户是不需要的
            if (0 == logininfo.getType()) {
                // 就是后台用户 那么它就应该有 permission 和menu
                // 根据logininfoid查询permission
                List<String> permissions = permissionMapper.findByLogininId(logininfo.getId());
                // 根据logininfoid 查询 menu
                List<Menu> menus = menuMapper.findByLoginfoId(logininfo.getId());
                userInfo.setPermissions(permissions);
                userInfo.setMenus(menus);
                map.put("permissions", permissions);
                map.put("menus", menus);

                Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
                if (null != employee && null != employee.getShopId()) {
                    Shop shop = shopMapper.findById(employee.getShopId());
                    userInfo.setShop(shop);
                }

            }

            String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 30);

            //5.返回在前端
            logininfo.setSalt(null);
            logininfo.setPassword(null);

            map.put("token",token);
            map.put("logininfo", logininfo);
        }catch (Exception e) {
            e.printStackTrace();
        }
            return map;
        }


//    private HashMap<String, Object> getMap(Logininfo logininfo) {
//        //4.保存在redis里
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token, logininfo,30, TimeUnit.MINUTES);
//
//        //5.返回在前端
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("token",token);
//        map.put("logininfo", logininfo);
//
//        return map;
//    }

    //微信扫码登录
    @Override
    public AjaxResult wechat(WechatDto dto) {
        //1校验
        //调第二个接口
        String s = HttpUtil.httpGet(String.format(LoginKou.SECOND_URL, LoginKou.WX_APP_ID, LoginKou.WX_SECRET, dto.getCode()));
        if(StringUtils.isBlank(s)){
            log.info("接口调取失败");
            throw new BussinessException("网络加载中，请稍后再试");
        }
        //将字符串转换成json
        JSONObject jsonObject = JSONObject.parseObject(s);
//取出access_token和openid
        String token = jsonObject.getString("access_token");
        if(StringUtils.isBlank(token)){
            log.info("获取token失败");
            throw new BussinessException("网络加载中，请稍后再试");
        }
        String openid = jsonObject.getString("openid");
        Wxuser wxuser= wxuserMapper.findByOpen(openid);
        if(null!=wxuser&& null != wxuser.getUserId()){
            // 直接登陆 根据userId 查询logininfo数据
            Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
            return AjaxResult.me().success(this.getMap(logininfo));

        }
        StringBuilder sb = new StringBuilder();
        sb.append("?accessToken=")
                .append(token)
                .append("&openId=")
                .append(openid);
        return AjaxResult.me().fail("nobinder").setResultObj(sb.toString());

    }

    @Override
    public HashMap<String, Object> binder(BinderDto dto) {
    //1.参数校验
        //2.验证码
        String o = (String) redisTemplate.opsForValue().get(String.format(LoginKou.BINDER_PHONE_KEY, dto.getPhone()));
        if(StringUtils.isBlank(o)||!o.equals(dto.getVerifyCode())){
            throw new BussinessException("验证码已经过期");
        }
        //3.调用第三个接口
        String s = HttpUtil.httpGet(String.format(LoginKou.THIRD_URL, dto.getAccessToken(), dto.getOpenId()));
        if(StringUtils.isBlank(s)){
            log.info("获取失败");
            throw new BussinessException("网络加载中，请稍后再试");
        }
        Wxuser wxuser = JSONObject.parseObject(s, Wxuser.class);
        if (null == wxuser){
            log.info("调用微信接口失败！");
            throw new BussinessException("网络繁忙，请稍后重试！");
        }
        //4.判断User里是否有参数
        User user = userMapper.finfByphone(dto.getPhone());
        Logininfo logininfo = new Logininfo();

        if(null==user){
            user = dto.getUser();
            // 创建 logininfo对象 并添加
            BeanUtils.copyProperties(user,logininfo);
            logininfo.setType(1);
            logininfo.setDisable(1);
            logininfoMapper.add(logininfo);
            // 将logininfoid绑定到user对象上 并执行添加
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        } else {
            logininfo = logininfoMapper.findByUserId(user.getId());
        }

        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        //如果没有添加三张表
        return getMap(logininfo);
    }

    public static void main(String[] args) {
        String str = StrUtils.getComplexRandomString(32);
        String s = MD5Utils.encrypByMd5(str + "2");
        System.out.println(str);
        System.out.println(s);
    }
}
